from exts import db
from datetime import datetime


class UserModel(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    username = db.Column(
        db.String(64), nullable=False, comment='用户名'
    )
    password = db.Column(
        db.String(200), nullable=False, comment='密码'
    )
    email = db.Column(
        db.String(64), unique=True, nullable=False, comment='邮箱'
    )
    join_time = db.Column(
        db.DateTime, default=datetime.now, comment='注册时间'
    )


class EmailCaptchaModel(db.Model):
    __tablename__ = 'email_captcha'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='验证码ID')
    email = db.Column(
        db.String(64), nullable=False, comment='邮箱'
    )
    captcha = db.Column(
        db.String(6), nullable=False, comment='验证码'
    )
    used = db.Column(
        db.Boolean, default=False, comment='是否使用过'
    )
    join_time = db.Column(
        db.DateTime, default=datetime.now, comment='注册时间'
    )


class QuestionModel(db.Model):
    __tablename__ = 'question'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='问题ID')
    title = db.Column(
        db.String(64), nullable=False, comment='问题标题'
    )
    content = db.Column(
        db.Text, nullable=False, comment='问题内容'
    )
    author_id = db.Column(
        db.Integer, db.ForeignKey('user.id'), nullable=False, comment='作者ID'
    )
    author = db.relationship('UserModel', backref='questions')  # 反向引用
    join_time = db.Column(
        db.DateTime, default=datetime.now, comment='注册时间'
    )


class AnswerModel(db.Model):
    __tablename__ = 'answer'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='回答ID')
    content = db.Column(
        db.Text, nullable=False, comment='回答内容'
    )
    join_time = db.Column(
        db.DateTime, default=datetime.now, comment='发布时间'
    )
    question_id = db.Column(
        db.Integer, db.ForeignKey('question.id'), nullable=False, comment='问题ID'
    )
    question = db.relationship('QuestionModel',
                               backref=db.backref('answers', lazy='dynamic', order_by=join_time.desc()))  # 反向引用
    author_id = db.Column(
        db.Integer, db.ForeignKey('user.id'), nullable=False, comment='作者ID'
    )
    author = db.relationship('UserModel', backref='answers')  # 反向引用
